package com.biz.primus.ms.commodity.service.frontend;

import com.alibaba.fastjson.JSONArray;
import com.biz.primus.base.exception.utils.AssertUtils;
import com.biz.primus.commodity.enums.GoodsKind;
import com.biz.primus.commodity.exception.CommodityExceptionType;
import com.biz.primus.commodity.vo.GroupProductDetailVo;
import com.biz.primus.commodity.vo.GroupProductVo;
import com.biz.primus.commodity.vo.backend.GroupProductItemItemVo;
import com.biz.primus.commodity.vo.backend.GroupProductItemQueryVo;
import com.biz.primus.commodity.vo.backend.ProductVo;
import com.biz.primus.common.utils.CopyUtils;
import com.biz.primus.common.utils.StringUtil;
import com.biz.primus.common.vo.SpringPageVO;
import com.biz.primus.ms.base.vo.SpringPageToSpringPageVO;
import com.biz.primus.ms.commodity.dao.po.GroupProduct;
import com.biz.primus.ms.commodity.dao.po.GroupProductItem;
import com.biz.primus.ms.commodity.dao.po.Product;
import com.biz.primus.ms.commodity.dao.repository.product.GroupProductItemRepository;
import com.biz.primus.ms.commodity.dao.repository.product.GroupProductRepository;
import com.biz.primus.ms.commodity.dao.repository.product.ProductRepository;
import com.biz.primus.ms.commodity.dao.specification.GroupProductItemSpecification;
import com.biz.primus.ms.commodity.trans.GroupProductItem2GroupProductItemItemVo;
import com.biz.primus.ms.commodity.trans.Product2ProductVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 组合商品service
 * @author wan
 */
@Service
@Slf4j
public class GroupProductService extends AbstractCommodityService{

    private final GroupProductItemRepository groupProductItemRepository;
    private final GroupProductRepository groupProductRepository;
    private final ProductRepository productRepository;

    public GroupProductService(GroupProductItemRepository groupProductItemRepository,
                               GroupProductRepository groupProductRepository,
                               ProductRepository productRepository){
        this.groupProductItemRepository = groupProductItemRepository;
        this.groupProductRepository = groupProductRepository;
        this.productRepository = productRepository;
    }


    public SpringPageVO<GroupProductItemItemVo> findGroupProductList(GroupProductItemQueryVo groupProductDetailVo){
        Page<GroupProductItem> all = groupProductItemRepository.findAll(new GroupProductItemSpecification(groupProductDetailVo), groupProductDetailVo.toPageRequest());
        return SpringPageToSpringPageVO.of(all, new GroupProductItem2GroupProductItemItemVo());
    }


    public List<ProductVo> findGroupProductSelectList() {
        List<Product> list = productRepository.findAll(new Specification<Product>() {
            @Override
            public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                cq.orderBy(cb.desc(root.get("id")));
                Predicate predicate = cb.equal(root.get("isRapidProduct").as(boolean.class),false);
                cq.where(predicate);
                return cq.getRestriction();
            }
        });
        return Lists.transform(list,new Product2ProductVo());
    }

    public void save(GroupProductVo gp) {
        String type = gp.getType();
        //0新增,1编辑
        if(StringUtils.equals("0",type)){
            this.saveGP(gp);
        }else{
            this.updateGP(gp);
        }
    }
    public void updateGP(GroupProductVo gp){

        String id = gp.getId();
        GroupProductItem one = groupProductItemRepository.findOne(Long.parseLong(id));
        AssertUtils.notNull(one, CommodityExceptionType.PRODUCT_NOT_FOUND, "组合商品不存在");

        GroupProduct groupProduct = one.getParent();

        List<GroupProductItem> itemList = groupProduct.getItemList();
        itemList.clear();
        groupProductRepository.save(groupProduct);
        //商品明细
        String productJson = gp.getProductJson();
        List<GroupProductVo> pvs = JSONArray.parseArray(productJson, GroupProductVo.class);
        //构造itemList
        itemList = this.createGroupProductItem(pvs, groupProduct);

        groupProductItemRepository.save(itemList);

    }
    public void saveGP(GroupProductVo gp){
        //商品组code
        String productCode = gp.getProductCode();

        //商品明细
        String productJson = gp.getProductJson();

        AssertUtils.isTrue(StringUtils.isNotBlank(productCode), CommodityExceptionType.COMMON_EXCEPTION, "商品组合ID为空");
        AssertUtils.isTrue(StringUtils.isNotBlank(productCode) && productCode.startsWith("ZH"),
                CommodityExceptionType.COMMON_EXCEPTION, "商品组合必须以ZH开头");
        AssertUtils.isTrue(StringUtils.isNotBlank(productJson), CommodityExceptionType.COMMON_EXCEPTION, "没有选择商品");

        List<GroupProductVo> pvs = JSONArray.parseArray(productJson, GroupProductVo.class);

        //组合商品
        Product product = productRepository.findByProductCode(productCode);
        AssertUtils.isNull(product,CommodityExceptionType.COMMON_EXCEPTION,"组合商品已经存在");

        product = new Product();
        product.setId(idService.getNextId());
        product.setProductCode(productCode);
        product.setGoodsKind(GoodsKind.NORMAL);
        product.setGoodsSpec("");
        product.setName("");
        product.setIsRapidProduct(true);
        product.setUnitName("");


        //组合商品
        GroupProduct groupProduct = new GroupProduct();
        groupProduct.setId(idService.getNextId());
        groupProduct.setProduct(product);

        //包含的组合项
        List<GroupProductItem> itemList = this.createGroupProductItem(pvs,groupProduct);
        groupProduct.setItemList(itemList);

        product.setGroupProduct(groupProduct);
        productRepository.save(product);
    }

    public List<GroupProductItem> createGroupProductItem(List<GroupProductVo> pvs,GroupProduct groupProduct){
        List<GroupProductItem> itemList = new ArrayList<>();
        for (GroupProductVo pv : pvs) {
            String productId = pv.getProductId();
            Integer quantity = pv.getQuantity();
            Integer priceFactor = pv.getPriceFactor();
            //根据productId查询product
            Product productQuery = productRepository.getOne(Long.parseLong(productId));
            //组合商品(商品项)
            GroupProductItem groupProductItem = new GroupProductItem();
            groupProductItem.setId(idService.getNextId());
            groupProductItem.setParent(groupProduct);
            groupProductItem.setQuantity(quantity);
            groupProductItem.setPriceFactor(priceFactor);
            groupProductItem.setProduct(productQuery);
            itemList.add(groupProductItem);
        }
        return itemList;
    }

    public void del(String id) {

        //商品组
        GroupProductItem one = groupProductItemRepository.findOne(Long.parseLong(id));
        GroupProduct groupProduct = one.getParent();

        //删除关联的所有商品组
        List<GroupProductItem> itemList = groupProduct.getItemList();
        itemList.remove(one);

        groupProductItemRepository.delete(Long.parseLong(id));

        //当组合商品关联的商品被删除完了的时候,删除组合商品
        if(itemList.size() == 0){
            Product productCode = productRepository.findOne(groupProduct.getProduct().getId());
//            productRepository.delete(productCode.getId());
            groupProductRepository.delete(groupProduct.getId());
        }
    }

    public GroupProductVo findGroupProductById(String id) {
        GroupProductVo result = new GroupProductVo();
        //商品id
        GroupProductItem one = groupProductItemRepository.findOne(Long.parseLong(id));
        AssertUtils.notNull(one,CommodityExceptionType.COMMON_EXCEPTION,"组合商品不存在");

        GroupProduct groupProduct = one.getParent();

        result.setProductCode(groupProduct.getProduct().getProductCode());

        String productCodes = "";
        String productNames = "";

        List<GroupProductVo> list = new ArrayList();
        List<GroupProductItem> itemList = groupProduct.getItemList();
        for (GroupProductItem item : itemList) {
            productCodes += item.getProduct().getProductCode()+",";
            productNames += item.getProduct().getName()+",";

            GroupProductVo addVo = new GroupProductVo();
            addVo.setProductId(item.getProduct().getId().toString());
            addVo.setProductName(item.getProduct().getName());
            addVo.setQuantity(item.getQuantity());
            addVo.setPriceFactor(item.getPriceFactor());

            list.add(addVo);
        }
        result.setProductCodes(productCodes.substring(0,productCodes.length() -1 ));
        result.setProductNames(productNames.substring(0,productNames.length() -1 ));
        result.setItem(list);

        return result;
    }
}
